package bootstrap

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/kataras/golog"
	ginprometheus "github.com/zsais/go-gin-prometheus"
	"log"
	"net/http"
	"sdn-executor/api/middlewares"
	"sdn-executor/api/router"
	"sdn-executor/config"
	"strconv"
	"time"
)

func InitHTTP() error {
	conf := config.C().HTTPServer
	// 设置模式
	gin.SetMode(conf.Mode)

	e := gin.Default()
	e.Use(middlewares.Cors())
	if err := e.SetTrustedProxies([]string{}); err != nil {
		golog.Warnf("gin SetTrustedProxies failed. err: %+v", err)
	}

	// http prometheus exporter
	p := ginprometheus.NewPrometheus("gin")
	p.Use(e)

	// swagger
	// docs.SwaggerInfo.BasePath = "/api/v1"
	// e.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// recovery from panic
	// e.Use(gin.Logger(), gin.Recovery())

	router.AddRoutes(e)

	startHTTPServer(e)

	return nil
}

func startHTTPServer(handler http.Handler) {
	conf := config.C().HTTPServer
	addr := conf.Host + ":" + strconv.Itoa(int(conf.Port))
	golog.Infof("to start server. addr: %s", addr)

	srv := &http.Server{
		Addr:         addr,
		Handler:      handler,
		ErrorLog:     log.New(golog.Default.GetLevelOutput(conf.LogLevel), "", 0),
		ReadTimeout:  conf.ReadTimeoutMs * time.Millisecond,
		WriteTimeout: conf.WriteTimeoutMs * time.Millisecond,
	}

	if err := srv.ListenAndServe(); err != nil {
		panic(fmt.Sprintf("start http server failed. server addr: %s, err: %v", addr, err))
	}
}
